import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Rectangle;
import flash.geom.Point;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.Sprite;
import flash.ui.Keyboard;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.filters.GlowFilter;
import haxe.FastList;
import flash.events.MouseEvent;
import flash.net.SharedObject;
import flash.Lib;
import haxe.Log;

import flash.utils.Timer;
import haxe.Timer;
import flash.events.Event;
import flash.display.MovieClip;
import flash.media.SoundChannel;


import Images; 
import Scene;
import InstructionPage;
import UpgradePage;
import CreditsPage;
import OptionsPage;
import SoundPlayer;
import PauseMenu;
import Kongregate;
import Logo;
import CustomSprite;
import HelperMethods;
import GameData;
import Sounds;

class Main extends Sprite{
private var ground : Int;
private var currentLevel : Int;
private var Scenes : Array<Scene>;
//Because the levels are so similiar i can do this. It's probably be to have a class for each level that inherents from the scence. 
private var Level1 : Scene;

private var State : String;
private var savedData:SharedObject;
private var ContinueGameButton:Sprite;
private var StartGameButton:Sprite;
private var InfiniteGameButton:Sprite;
private var FreeModeButton:Sprite;
private var StartGameDifficulty:Sprite;
private var MainMenuButton:Sprite;
private var InstructionsButton:Sprite;
private var CreditsButton:Sprite;
private var OptionsButton:Sprite;
public var CenterCircle: Sprite;
public var CenterCircleText: TextField;
private var Title:TextField;
private var myLogo : Logo;


private var label1:TextField;
private var TryAgainPic:Sprite;
var myTimer:Timer;            
private var player:SoundPlayer;
private var BackgroundImage : Bitmap;
public var Instruction : InstructionPage;
public var Upgrade : UpgradePage;
public var Credit: CreditsPage;
public var OptionsMenu : OptionsPage;

var mKeyDown:Array<Bool>;
var pausePosition:Float;
var music:BackgroundMusic;
var volume:Bool;
var sound:Bool;
var framerate:Int;

var gameData:GameData;

var kongVar : CKongregate;

public function new(){
super();
haxe.remoting.AMFConnection.registerClassAlias("GameData",GameData);
Scenes = [];
getLevelData();

initLevels();

volume = true;
//Add Main to Current Flash
flash.Lib.current.addChild(this);
//Create Menu (own Class?)
Title = new TextField();
    
  Title.x = 50; Title.y = 20;
  Title.width = Constants.flashWidth-100; Title.height = Constants.flashHeight;
  Title.multiline = true;
  var myFormat:TextFormat = new TextFormat();
  myFormat.size = 25;
  myFormat.align = TextFormatAlign.CENTER;
  Title.defaultTextFormat = myFormat;
  
  Title.htmlText = "Circle Madness";

StartGameButton = new Sprite();
    StartGameButton.graphics.lineStyle(1);
    StartGameButton.graphics.beginFill(0xcc1367);
    StartGameButton.graphics.drawCircle(0, 0,50);
    StartGameButton.graphics.endFill();  
var buttonText = new TextField();
    buttonText.htmlText = "<font color='#FFFFFF' size='16'>Story Mode</font>";
    buttonText.selectable = false;
    buttonText.mouseEnabled = false;
    buttonText.x = -38;buttonText.y=-13;
    StartGameButton.addChild(buttonText);

StartGameButton.x = 345;
StartGameButton.y = 110;

StartGameButton.buttonMode = true;
StartGameButton.addEventListener(MouseEvent.ROLL_OVER,onStartGameHover);
StartGameButton.addEventListener(MouseEvent.ROLL_OUT,onHoverOut);
StartGameButton.addEventListener(MouseEvent.CLICK, onStartGameButtonClick);

StartGameDifficulty = new Sprite();
    StartGameDifficulty.graphics.lineStyle(1);
    StartGameDifficulty.graphics.beginFill(0xFFFFFF);
    StartGameDifficulty.graphics.drawCircle(0, 0,230);
    StartGameDifficulty.graphics.endFill();  

StartGameDifficulty.x = 400;
StartGameDifficulty.y = 245;

var easyGame = new Sprite();
    easyGame.graphics.lineStyle(1);
    easyGame.graphics.beginFill(0x00FF00);
    easyGame.graphics.drawCircle(0, 0,50);
    easyGame.graphics.endFill();
var text = new TextField();
    text.htmlText = "Easy";
    easyGame.addChild(text);
    text.x = -15;text.y =-10;
    text.selectable = false;
    text.mouseEnabled = false;

StartGameDifficulty.addChild(easyGame);
easyGame.x = -110;
easyGame.buttonMode = true;
easyGame.addEventListener(MouseEvent.CLICK, onEasyGameButtonClick);


var mediumGame = new Sprite();
    mediumGame.graphics.lineStyle(1);
    mediumGame.graphics.beginFill(0xFFFF00);
    mediumGame.graphics.drawCircle(0, 0,50);
    mediumGame.graphics.endFill();
var text = new TextField();
    text.htmlText = "Medium";
    mediumGame.addChild(text);
    text.x = -25;text.y =-10;
    text.selectable = false;
    text.mouseEnabled = false;

StartGameDifficulty.addChild(mediumGame);
mediumGame.x = 00;
mediumGame.buttonMode = true;
mediumGame.addEventListener(MouseEvent.CLICK, onMediumGameButtonClick);


var hardGame = new Sprite();
    hardGame.graphics.lineStyle(1);
    hardGame.graphics.beginFill(0xFF0000);
    hardGame.graphics.drawCircle(0, 0,50);
    hardGame.graphics.endFill();

var text = new TextField();
    text.htmlText = "Hard";
    hardGame.addChild(text);
    text.x = -15;text.y =-10;
    text.selectable = false;
    text.mouseEnabled = false;

StartGameDifficulty.addChild(hardGame);
hardGame.x = 110;
hardGame.buttonMode = true;
hardGame.addEventListener(MouseEvent.CLICK, onHardGameButtonClick);

ContinueGameButton = new Sprite();
    ContinueGameButton.graphics.lineStyle(1);
    ContinueGameButton.graphics.beginFill(0xf8320d);
    ContinueGameButton.graphics.drawCircle(0, 0,50);
    ContinueGameButton.graphics.endFill();  
var buttonText = new TextField();
    buttonText.htmlText = "<font size='15' color='#000000'>Continue Story</font>";
    buttonText.selectable = false;
    buttonText.mouseEnabled = false;
    buttonText.x = -50;buttonText.y=-12;
    ContinueGameButton.addChild(buttonText);
ContinueGameButton.x = 455;
ContinueGameButton.y = 110;

ContinueGameButton.buttonMode = true;
ContinueGameButton.addEventListener(MouseEvent.CLICK, onContinueGameButtonClick);
ContinueGameButton.addEventListener(MouseEvent.ROLL_OUT,onHoverOut);
ContinueGameButton.addEventListener(MouseEvent.ROLL_OVER,onContinueGameHover);

InfiniteGameButton = new Sprite();
    InfiniteGameButton.graphics.lineStyle(1);
    InfiniteGameButton.graphics.beginFill(0xed4c0d);
    InfiniteGameButton.graphics.drawCircle(0, 0,50);
    InfiniteGameButton.graphics.endFill();  
var buttonText = new TextField();
    buttonText.htmlText = "<font size='16'>Infinite Game</font>";
    buttonText.selectable = false;
    buttonText.mouseEnabled = false;
    buttonText.x = -48;buttonText.y=-12;
    InfiniteGameButton.addChild(buttonText);

InfiniteGameButton.x = 520;
InfiniteGameButton.y = 200;
InfiniteGameButton.buttonMode = true;
InfiniteGameButton.addEventListener(MouseEvent.CLICK, onInfiniteModeButtonClick);
InfiniteGameButton.addEventListener(MouseEvent.ROLL_OVER,onInfiniteModeHover);
InfiniteGameButton.addEventListener(MouseEvent.ROLL_OUT,onHoverOut);



FreeModeButton = new Sprite();
    FreeModeButton.graphics.lineStyle(1);
    FreeModeButton.graphics.beginFill(0x640981);
    FreeModeButton.graphics.drawCircle(0, 0,50);
    FreeModeButton.graphics.endFill();  
var buttonText = new TextField();
    buttonText.htmlText = "<font size='16' color='#FFFFFF'>Free Mode</font>";
    buttonText.selectable = false;
    buttonText.mouseEnabled = false;
    buttonText.x = -40;buttonText.y=-12;
    FreeModeButton.addChild(buttonText);

FreeModeButton.x = 275;
FreeModeButton.y = 200;

FreeModeButton.buttonMode = true;
FreeModeButton.addEventListener(MouseEvent.CLICK, onFreeModeButtonClick);
FreeModeButton.addEventListener(MouseEvent.ROLL_OVER,onFreeModeHover);
FreeModeButton.addEventListener(MouseEvent.ROLL_OUT,onHoverOut);

InstructionsButton = new Sprite();
    InstructionsButton.graphics.lineStyle(1);
    InstructionsButton.graphics.beginFill(0xf7f732);
    InstructionsButton.graphics.drawCircle(0, 0,50);
    InstructionsButton.graphics.endFill();  
var buttonText = new TextField();
    buttonText.htmlText = "<font size='14' color='#111111'>Instructions</font>";
    buttonText.selectable = false;
    buttonText.mouseEnabled = false;
    buttonText.x = -33;buttonText.y=-10;
    InstructionsButton.addChild(buttonText);

InstructionsButton.x = 495;
InstructionsButton.y = 305;


InstructionsButton.buttonMode = true;
InstructionsButton.addEventListener(MouseEvent.CLICK, onInstrutionsButtonClick);
InstructionsButton.addEventListener(MouseEvent.ROLL_OUT,onHoverOut);
InstructionsButton.addEventListener(MouseEvent.ROLL_OVER,onInstrutionsHover);

Instruction = new InstructionPage();
Instruction.addEventListener("Back",onInstrutionsBack);

Upgrade = new UpgradePage();
Upgrade.addEventListener("Back",onUpgradeBack);

CreditsButton = new Sprite();
    CreditsButton.graphics.lineStyle(1);
    CreditsButton.graphics.beginFill(0x1b077f);
    CreditsButton.graphics.drawCircle(0, 0,50);
    CreditsButton.graphics.endFill();  
var buttonText = new TextField();
    buttonText.htmlText = "<font size='17' color='#CCCCCC'>Credits</font>";
    buttonText.selectable = false;
    buttonText.mouseEnabled = false;
    buttonText.x = -29;buttonText.y=-12;
    CreditsButton.addChild(buttonText);

CreditsButton.x = 305;
CreditsButton.y = 305;

CreditsButton.buttonMode = true;
CreditsButton.addEventListener(MouseEvent.CLICK, onCreditsButtonClick);
CreditsButton.addEventListener(MouseEvent.ROLL_OUT,onHoverOut);
CreditsButton.addEventListener(MouseEvent.ROLL_OVER,onCreditsHover);

Credit = new CreditsPage();
Credit.addEventListener("Back",onCreditsBack);

OptionsButton = new Sprite();
    OptionsButton.graphics.lineStyle(1);
    OptionsButton.graphics.beginFill(0x0a8c37);
    OptionsButton.graphics.drawCircle(0, 0,50);
    OptionsButton.graphics.endFill();  
var buttonText = new TextField();
    buttonText.htmlText = "<font size='16' color='#000000'>Options</font>";
    buttonText.selectable = false;
    buttonText.mouseEnabled = false;
    buttonText.x = -30;buttonText.y=-12;
    OptionsButton.addChild(buttonText);

OptionsButton.x = 400;
OptionsButton.y = 365;

OptionsButton.buttonMode = true;
OptionsButton.addEventListener(MouseEvent.CLICK, onOptionsButtonClick);
OptionsButton.addEventListener(MouseEvent.ROLL_OUT,onHoverOut);
OptionsButton.addEventListener(MouseEvent.ROLL_OVER,onOptionsHover);

OptionsMenu = new OptionsPage();
OptionsMenu.addEventListener("Back",onOptionsMenuBack);
OptionsMenu.addEventListener("ResetSavedData",onOptionsMenuResetSavedData);
OptionsMenu.addEventListener("VolumeToggle",onOptionsMenuVolumeToggle);
OptionsMenu.addEventListener("SoundEffectsToggle",onOptionsMenuSoundEffectsToggle);
this.addEventListener(Event.ENTER_FRAME, OnEnter);
// myTimer = new Timer(12);
//   myTimer.addEventListener("timer", OnEnter);
//   myTimer.start();

CenterCircle = new Sprite();
    CenterCircle.graphics.lineStyle(1);
    CenterCircle.graphics.beginFill(0xFFFFFF);
    CenterCircle.graphics.drawCircle(0, 0,70);
    CenterCircle.graphics.endFill();  
    CenterCircleText = new TextField();
    CenterCircleText.htmlText = "<font size='16' color='#000000'></font>";
    CenterCircleText.autoSize = TextFieldAutoSize.CENTER;
    CenterCircleText.width = 100;
    CenterCircleText.wordWrap = true;
    CenterCircleText.multiline = true;
    CenterCircleText.selectable = false;
    CenterCircleText.mouseEnabled = false;
    CenterCircleText.x = -48;
    CenterCircle.addChild(CenterCircleText);
    CenterCircleText.y=-5+((-CenterCircleText.length));

CenterCircle.x = 400;
CenterCircle.y = 225;

OptionsButton.buttonMode = true;
OptionsButton.addEventListener(MouseEvent.CLICK, onOptionsButtonClick);


  label1 = new TextField();
  label1.x = 0; label1.y = 0;
  label1.width = Constants.flashWidth; label1.height = 100;
  label1.autoSize = TextFieldAutoSize.CENTER;

TryAgainPic = new Sprite();
TryAgainPic.graphics.lineStyle(1);
TryAgainPic.graphics.beginFill(0xFFFFFF);
TryAgainPic.graphics.drawCircle(0, 0, 50);
TryAgainPic.graphics.endFill(); 
TryAgainPic.x = 400;
TryAgainPic.y = 80;

var buttonText = new  TextField();
    buttonText.htmlText = "<font size='16' color='#000000'>Yay!</font>";
    buttonText.selectable = false;
    buttonText.mouseEnabled = false;
    buttonText.x = -30;buttonText.y=-12;
    TryAgainPic.addChild(buttonText);

MainMenuButton  = new Sprite();
MainMenuButton.graphics.beginBitmapFill(new MainMenu());
MainMenuButton.graphics.drawRect(0, 0, 250 ,48);
MainMenuButton.x = 285;
MainMenuButton.y = 135;
MainMenuButton.buttonMode = true;
MainMenuButton.addEventListener(MouseEvent.CLICK, onMainMenuButtonClick);

//The State Will determine whether to load a level, or show Main Menu, or whatever.  Used in the OnEnterEvent.
State = "LoadMainMenu";
//State = "LoadMainMenu";
music = new BackgroundMusic();
//preloader = new PreloaderHost();
BackgroundImage = new Bitmap(new Background());
player = new SoundPlayer(music);

volume = true;
sound = true;
myLogo = new Logo();
addChild(myLogo);
try
{
kongVar = new CKongregate();
}
catch (msg:Dynamic)
{
}
mKeyDown = [];
stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyDown );
stage.addEventListener(KeyboardEvent.KEY_UP, OnKeyUp );

//preloader.addEventListener(Event.ENTER_FRAME, OnMovieEnter);
}

public function OnKeyUp (event:KeyboardEvent)
    {
      mKeyDown[event.keyCode] = false;
      //lastUp = event.keyCode;
    }

public function OnKeyDown(event:KeyboardEvent)
   {
      // When a key is held down, multiple KeyDown events are generated.
      // This check means we only pick up the first one.
      if (!mKeyDown[event.keyCode])
      {
         // Store for use in game
         mKeyDown[event.keyCode] = true;
	  //I do this here, because if they hold down P,
	 // it won't pause and unpause constantly.
	  if(mKeyDown[ 77 ] == true)
	  {
	  volume = !volume;
	  }
      }
  }

function loadMenu()
{
  addChild(BackgroundImage);
  addChild(Title);
  addChild(StartGameButton);
  addChild(InfiniteGameButton);
  addChild(FreeModeButton);
  addChild(ContinueGameButton);
  addChild(InstructionsButton);
  addChild(CreditsButton);
  addChild(OptionsButton);
  addChild(CenterCircle );
}
function removeMenu()
{
  removeChild(Title);
  removeChild(StartGameButton);
  removeChild(InfiniteGameButton);
  removeChild(FreeModeButton);
  removeChild(ContinueGameButton);
  removeChild(BackgroundImage);
  removeChild(InstructionsButton);
  removeChild(CreditsButton);
  removeChild(OptionsButton);
  removeChild(CenterCircle);
}

//Change to stat Menu
function loadTryAgainMenu(text:String)
{
  addChild(label1);
  label1.htmlText = "<font size='15'>" + text + "</font>";
  addChild(MainMenuButton);
  addChild(TryAgainPic);
}
function removeTryAgainMenu()
{
 removeChild(label1);
 removeChild(MainMenuButton);
 removeChild(TryAgainPic);
}
function initLevels()
{

//Postion, MoveSpeed, JumpSpeed, AttackSpeed, Health, Bitmap)

}

function OnEnter(e:flash.events.Event)
{
if(player !=null)
  {
      if(!volume)
      {
	 pausePosition = player.getPosition();
         player.stop();         
      }
      else
      {
        player.play(pausePosition);
      }
  }
if(State == "LoadMainMenu")
{
 loadMenu();
 State = "MainMenu";
}
if(State == "MainMenu" )
   {

     return;
   }
if(State == "TryAgain")
  {
    //AnimateTryAgainPic();
    return;
  }
if(State == "InitLoad")
  {
   
//    addChild(preloader);
  //  preloader.play();
    State = "InitLoading";
  }
if(State == "InitLoading")
   { 
    //Always Playing. Possible error with swfmill
    //Skipping for now.
 
//     if(!preloader.playing)
//        {
//         preloader.stop();
//         removeChild(preloader);
	myLogo.start();
        State = "LoadingLogo";
//        }

   }
if(State == "LoadingLogo")
  {

     if(!myLogo.play())
     {
       State = "LoadMainMenu";
     }
  }
if(State == "InfiniteMode")
  {
Level1 = new Scene(10,100,
		     0,0,
		     0,0,1,
		     0);
loadCurrentLevel(false);
  }
if(State == "FreeMode")
  {
Level1 = new Scene(10,100,
		     0,0,
		     0,0,1,
		     -1);
loadCurrentLevel(false);
  }
if(State == "StartGame")
   {
    Level1 = new Scene(gameData.ShipSize,gameData.MaxHealth,
		     gameData.PowerUpAppearanceRate,gameData.InvincibilityLength,
		     gameData.PowerUpFadeRate,gameData.MoneyMultiplier,gameData.ShotsFiredRate,
		     gameData.Difficulty);
    loadCurrentLevel(false);
   }
if(State == "ContinueGame")
   {
   Level1 = new Scene(gameData.ShipSize,gameData.MaxHealth,
		     gameData.PowerUpAppearanceRate,gameData.InvincibilityLength,
		     gameData.PowerUpFadeRate,gameData.MoneyMultiplier,gameData.ShotsFiredRate,
		     gameData.Difficulty);
    loadCurrentLevel(true);
   }
if(State == "Playing")
   {
    if(Scenes[currentLevel-1] != null)
    {
      if(Scenes[currentLevel-1].running)
      {
      if(!volume)
      {
	 pausePosition = player.getPosition();
         player.stop();         
      }
      else
      {
        player.play(pausePosition);
      }
      return;
      }
      else if(Scenes[currentLevel-1].State == 'EndScreen')
      {
      //Load Upgrades screem

      return;
      }
      else
      { 
      return;
      } 
        
    }
    loadCurrentLevel(true);
   }
// try
// {
// //             var req:flash.net.URLRequest = new flash.net.URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3");
// //             
// //             Sound.load(req);
// var music = new BackgroundMusic();            
//             music.play();
// }
// catch (err:flash.Error)
// {
// trace(err.message);
// }


}
public function AnimateTryAgainPic()
{
var randomNumber = Std.random(24);
if(randomNumber == 1)
  TryAgainPic.x = TryAgainPic.x + 5;
if(randomNumber == 2)
  TryAgainPic.x = TryAgainPic.x - 5;

}

//Loads Level based on Current Level
public function loadCurrentLevel(inContinue:Bool) : Bool
{
  currentLevel = 1;
  
  Scenes[currentLevel-1] = null;
  Scenes[currentLevel-1] = Level1;
  
  Scenes[currentLevel-1].addEventListener("SceneFinished",onSceneFinished);
  Scenes[currentLevel-1].addEventListener("SceneWon",onSceneWon);
  Scenes[currentLevel-1].addEventListener("SceneQuit",onSceneQuit);

  State = "Playing";
  Level1.Load();
// Scenes[currentLevel-1].Load(volume,sound,inContinue);
Scenes[currentLevel-1].pauseMenu.renderVolume(volume);
// Scenes[currentLevel-1].pauseMenu.renderSoundEffects(sound);
Scenes[currentLevel-1].addEventListener("VolumeToggle",onSceneVolumeToggle);
// Scenes[currentLevel-1].addEventListener("SoundEffectsToggle",onSceneSoundEffectsToggle);
return true;
}


public function getLevelData()
{
  currentLevel = 1;
  pausePosition = 0;
  gameData = new GameData();

  //Load Save Data
  savedData = SharedObject.getLocal("GameData");
  if(savedData.data.gameData != null)
  {
    gameData = savedData.data.gameData;
  }
}
public function removeClip(preloader)
{
 removeChild(preloader);
}

  private function onHoverOut(event:MouseEvent)
  {	
    CenterCircleText.htmlText = "<font size='16' color='#000000'></font>";
  }

private function onStartGameButtonClick(event:MouseEvent) {
currentLevel = 1;
pausePosition = 0;
addChild(StartGameDifficulty);
//removeMenu();
//State = "StartGame";
}
 private function onStartGameHover(event:MouseEvent)
  {
    CenterCircleText.htmlText = "<font size='16' color='#000000'>I use the term \"Story\" very lightly.</font>";
    CenterCircleText.y = -5+((-CenterCircleText.length));
  }


private function onFreeModeButtonClick(event:MouseEvent)
{
removeMenu();
State = "FreeMode";
}

 private function onFreeModeHover(event:MouseEvent)
  {
    CenterCircleText.htmlText = "<font size='14' color='#000000'>No Enemies. No Upgrades. See how many Shots you can fire in one setting.</font>";
    CenterCircleText.y = -5+((-CenterCircleText.length)*.7);
  }

private function onInfiniteModeButtonClick(event:MouseEvent)
{
  removeMenu();
  State = "InfiniteMode";
}

private function onInfiniteModeHover(event:MouseEvent)
 {
    CenterCircleText.htmlText = "<font size='14' color='#000000'>Hold off a swarm of Infinitly generated enemies as long as you can.</font>";
    CenterCircleText.y = -5+((-CenterCircleText.length)*.7);
 }

private function onEasyGameButtonClick(event:MouseEvent)
{
removeChild(StartGameDifficulty);
removeMenu();
State = "StartGame";
gameData = new GameData();
gameData.Difficulty = 1;
}

private function onMediumGameButtonClick(event:MouseEvent)
{
removeChild(StartGameDifficulty);
removeMenu();
State = "StartGame";
gameData = new GameData();
gameData.Difficulty = 2;
}

private function onHardGameButtonClick(event:MouseEvent)
{
removeChild(StartGameDifficulty);
removeMenu();
State = "StartGame";
gameData = new GameData();
gameData.Difficulty = 3;
}

private function onContinueGameButtonClick(event:MouseEvent) {


removeMenu();
State = "ContinueGame";
}

private function onContinueGameHover(event:MouseEvent)
{
    CenterCircleText.htmlText = "<font size='14' color='#000000'>Continue an Existing Game</font>";
    CenterCircleText.y = -5+((-CenterCircleText.length)*.7);
}

private function onMainMenuButtonClick(event:MouseEvent) {
removeTryAgainMenu();
State = "LoadMainMenu";
}
private function onInstrutionsButtonClick(event:MouseEvent) {
removeMenu();
addChild(Instruction);
}

private function onInstrutionsHover(event:MouseEvent)
{
    CenterCircleText.htmlText = "<font size='14' color='#000000'>Keyboard Moves. Space fires. Click For More</font>";
    CenterCircleText.y = -5+((-CenterCircleText.length)*.7);
}

private function onCreditsButtonClick(event:MouseEvent) {
removeMenu();
addChild(Credit);
}

private function onCreditsHover(event:MouseEvent)
{
    CenterCircleText.htmlText = "<font size='14' color='#000000'>This is where I give people credit for making the game. Mostly me.</font>";
    CenterCircleText.autoSize = TextFieldAutoSize.CENTER;
    CenterCircleText.y = -5+((-CenterCircleText.length)*.7);
}

private function onOptionsButtonClick(event:MouseEvent) {
removeMenu();
addChild(OptionsMenu);
OptionsMenu.renderVolume(volume);
OptionsMenu.renderSoundEffects(sound);
}

private function onOptionsHover(event:MouseEvent)
{
    CenterCircleText.htmlText = "<font size='14' color='#000000'>Disable Sound or Reset Saved Data</font>";
    CenterCircleText.y = -5+((-CenterCircleText.length)*.7);
}

private function onInstrutionsBack(event:InstructionPageEvent)
{
removeChild(Instruction);
loadMenu();
}

private function onUpgradeBack(event:UpgradePageEvent)
{
   var savedData = SharedObject.getLocal("GameData");
   savedData.data.gameData = gameData;
   savedData.flush();
removeChild(Upgrade);
Level1 = new Scene(gameData.ShipSize,gameData.MaxHealth,
		     gameData.PowerUpAppearanceRate,gameData.InvincibilityLength,
		     gameData.PowerUpFadeRate,gameData.MoneyMultiplier,gameData.ShotsFiredRate,
		     gameData.Difficulty);
loadCurrentLevel(true);
}

private function onSceneFinished(event:Event)
{
  gameData.Money += Scenes[currentLevel-1].TotalMoney;
  removeScenesEventListeners();
  Upgrade.gameData = gameData;
  addChild(Upgrade);
}

private function onSceneWon(event:Event)
{
  
  removeScenesEventListeners();
  loadTryAgainMenu("You Won");
      
          try
          {
	    if(gameData.Difficulty == 3)
	    {
	      kongVar.SubmitStat("HardBeaten",Scenes[currentLevel-1].numOfFrames);
	    }
	    if(gameData.Difficulty == 2)
	    {
	      kongVar.SubmitStat("MediumBeaten",Scenes[currentLevel-1].numOfFrames);
	    }
	    if(gameData.Difficulty == 1)
	    {
	      kongVar.SubmitStat("EasyBeaten",Scenes[currentLevel-1].numOfFrames);
	    }
          }
          catch(msg: Dynamic) 
	  {
           
          }
  State = "TryAgain";
}
private function removeScenesEventListeners()
{
  Scenes[currentLevel-1].removeEventListener("SceneFinished",onSceneFinished);
  Scenes[currentLevel-1].removeEventListener("SceneQuit", onSceneQuit);
  Scenes[currentLevel-1].removeEventListener("SceneWon", onSceneWon);
}
private function onSceneQuit(event:Event)
{
  removeScenesEventListeners();
  State = "InitLoading";
}
private function onOptionsMenuBack(event:OptionsPageEvent)
{
removeChild(OptionsMenu);
loadMenu();
}
private function onOptionsMenuVolumeToggle(event:OptionsPageEvent)
{
volume = !volume;
OptionsMenu.renderVolume(volume);
}
private function onOptionsMenuSoundEffectsToggle(event:OptionsPageEvent)
{
sound = !sound;
OptionsMenu.renderSoundEffects(sound);
}

private function onSceneVolumeToggle(event:PauseMenuEvent)
{
volume = !volume;
//Scenes[currentLevel-1].volume = volume;
Scenes[currentLevel-1].pauseMenu.renderVolume(volume);
}
private function onSceneSoundEffectsToggle(event:PauseMenuEvent)
{
sound = !sound;
// Scenes[currentLevel-1].sound = sound;
// Scenes[currentLevel-1].pauseMenu.renderSoundEffects(sound);
}
private function onOptionsMenuResetSavedData(event:OptionsPageEvent)
{
      savedData.data.gameData = new GameData();
      savedData.flush();
      getLevelData();
      pausePosition = 0;
      currentLevel = 1;
}
private function onCreditsBack(event:CreditsPageEvent)
{
removeChild(Credit);
loadMenu();
}

//Couldn't get preloader to work.
	    static function onEnterFrame(event : Event)
	    {
	        Log.trace("Downloaded " + Lib.current.root.loaderInfo.bytesLoaded + " of " + Lib.current.root.loaderInfo.bytesTotal + " bytes");
	 
	        if (Lib.current.root.loaderInfo.bytesLoaded >= Lib.current.root.loaderInfo.bytesTotal)
	        {
	            Lib.current.root.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
	            Log.trace("Preloading finished");
	            Lib.current.gotoAndStop("start");
                  // new Images();
	          var mainInstance:Main = new Main();
	        }
	    }

    static function main() {
// Log.trace("Starting preloader");
  //Lib.current.roott.addEventListener(Event.ENTER_FRAME, onEnterFrame);
try
{
 new Main();
}
catch (err:flash.Error)
{
trace(err.message);

}
      // Create the request object...
//       var loader = new flash.display.Loader();
//       // When the image is ready, instanciate the game class...
//       loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE,
//           function(_) { new Main(untyped loader.content.bitmapData); });
//       // Fire off the request and wait...
//       loader.load(new flash.net.URLRequest("img/file.gif"));
        //new Main();    
      
	
    }
}